package com.cqndt.disaster.device.service.data.impl;

import com.cqndt.disaster.device.dao.data.TabDeviceMapper;
import com.cqndt.disaster.device.dao.data.TabMonitorPersonMapper;
import com.cqndt.disaster.device.entity.data.TabMonitorPerson;
import com.cqndt.disaster.device.service.data.TabMonitorPersonService;
import com.cqndt.disaster.device.util.Result;
import com.cqndt.disaster.device.vo.data.TabMonitorPersonVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TabMonitorPersonImpl implements TabMonitorPersonService {

    @Autowired
    private TabMonitorPersonMapper tabMonitorPersonMapper;
    @Autowired
    private TabDeviceMapper tabDeviceMapper;

    @Override
    public Result getMonitorPerson(TabMonitorPersonVo vo) {
        List<TabMonitorPersonVo> monitorPerson = tabMonitorPersonMapper.getMonitorPerson(vo);
        Result result = new Result();
        result.setData(monitorPerson);
        result.setCode(0);
        result.setMsg("查询成功");
        return result;
    }

    @Override
    public Result getMonitorPersonList(TabMonitorPersonVo vo) {
        Result result = new Result();
        List<Map<String, Object>> list = tabMonitorPersonMapper.getMonitorPersonList(vo);
        List<Map<String, Object>> list1 = null;
        //--------------------------------------------------------------------
        //遍历list对象获得所有监测人id
        List<String> PersonId = new ArrayList<>();
        for (Map<String, Object> m : list) {
            PersonId.add(m.get("id").toString());
        }
        //如果没有该地区、账户没有监测人
        if (PersonId.size() == 0) {
            for (Map<String, Object> map : list) {
                map.replace("Address", map.get("Address"), map.get("cityName").toString() + map.get("countyName").toString() + map.get("codeName").toString());
                String address = map.get("cityName").toString() + map.get("countyName").toString() + map.get("codeName").toString();
                map.put("areaCode", map.get("cityCode").toString() + "," + map.get("countyCode").toString() + "," + map.get("code").toString());
                tabMonitorPersonMapper.updateAddress(address, map.get("id").toString());
            }
            PageHelper.startPage(vo.getPage(), vo.getLimit());
            PageHelper.orderBy("id desc");
            list1 = tabMonitorPersonMapper.getMonitorPersonList(vo);
        } else {

            //传回监测人数据 和 关联了设备的监测人 对比：
            // 已关联的监测人集合
            List<Integer> isHave = new ArrayList<>();
            // 未关联的监测人集合
            List<Integer> noHave = new ArrayList<>();
            //查询所有关联了设备的监测人
            List<String> allMonitorPersonGroup = tabDeviceMapper.getAllMonitorPersonGroup();
            //传回监测人数据 和 关联了设备的监测人 对比
            for (String all : allMonitorPersonGroup) {
                int count = 0;
                for (String perId : PersonId) {
                    if (perId.equals(all)) {
                        isHave.add(Integer.parseInt(all));
                        break;
                    }
                    count++;
                    if (!StringUtils.isEmpty(all) && count == PersonId.size() && !"null".equals(all)) {
                        noHave.add(Integer.parseInt(all));
                    }
                }
            }

            if (isHave.size() != 0) {
                //获取本页所有监测人下面所有的设备名称  返回设备名 设备id  监测人id
                List<Map<String, Object>> deviceName = tabDeviceMapper.getDeviceName(PersonId);

                // 用来存储对应监测人的设备
                Map<String, String> deviceMap = new HashMap<>();

                // 存储所有设备的id
                List<String> deviceId = new ArrayList<>();

                //组装对应监测人的所有设备
                //deviceName:[{"1","A"},{"1","B"},{"2","c"}]   执行完后的结果：deviceMap:[{"1","A,B"},{"2","c"}]
                for (Map<String, Object> map : deviceName) {
                    String deName = map.get("device_name").toString();
                    if (deviceMap.containsKey(map.get("monitor_person").toString())) {
                        deName = deviceMap.get(map.get("monitor_person").toString()) + "," + deName;
                    }
                    deviceMap.put(map.get("monitor_person").toString(), deName);
                    //获取设备id
                    deviceId.add(map.get("id").toString());
                }

                //根据设备id查询设备对应的项目  返回 项目名称 设备id
                List<Map<String, Object>> projectList = tabDeviceMapper.getProjectName(deviceId);

                //用来存储监测人对应的项目
                Map<String, String> projectMap = new HashMap<>();

                // 先循环设备名称list {"1": ""A,B", "2" : "C"}
                // 在循环项目名称list
                //最终结果类似于：{"监测人" : "项目A"}
                for (Map<String, Object> map : deviceName) {
                    //projectList:[{"XA", "A"},{"XB", "B"},{"XA", "C"}]  项目A：设备A
                    for (Map<String, Object> projectNameMap : projectList) {
                        if (map.get("id").toString().equals(projectNameMap.get("device_id").toString())) {
                            String proName = projectNameMap.get("project_name").toString();
                            if (projectMap.containsKey(map.get("monitor_person").toString())) {
                                proName = projectMap.get(map.get("monitor_person").toString()) + "," + proName;
                            }
                            projectMap.put(map.get("monitor_person").toString(), proName);
                        }
                        //最终结果 projectMap：{"1":"XA,XB", "2":"XA"}
                    }
                }

                //--------------------------------------------------------------------
                for (Map<String, Object> map : list) {
                    map.replace("Address", map.get("Address"), map.get("cityName").toString() + map.get("countyName").toString() + map.get("codeName").toString());
                    String address = map.get("cityName").toString() + map.get("countyName").toString() + map.get("codeName").toString();
                    map.put("areaCode", map.get("cityCode").toString() + "," + map.get("countyCode").toString() + "," + map.get("code").toString());
                    tabMonitorPersonMapper.updateAddress(address, map.get("id").toString());
                }
                PageHelper.startPage(vo.getPage(), vo.getLimit());
                PageHelper.orderBy("id desc");
                list1 = tabMonitorPersonMapper.getMonitorPersonList(vo);
                for (Map map : list1) {
                    //将对应的设备名称存入 相应的监测人map之中
                    boolean a = false;
                    for (Map.Entry<String, String> dMap : deviceMap.entrySet()) {
                        String id = map.get("id").toString();
                        String key = dMap.getKey();
                        if (id.equals(key)) {
                            a = true;
                            String value = dMap.getValue();
                            map.put("deviceName", value);
                        }
                    }
                    if (a == false) {
                        map.put("deviceName", "");
                    }

                    //将对应的项目名称存入 相应的监测人map之中
                    boolean b = false;
                    for (Map.Entry<String, String> pMap : projectMap.entrySet()) {
                        String id = map.get("id").toString();
                        String key = pMap.getKey();
                        if (id.equals(key)) {
                            b = true;
                            String value = pMap.getValue();
                            map.put("projectName", value);
                        }
                        if (b == false) {
                            map.put("projectName", "");
                        }
                    }
                }
            } else if (noHave.size() != 0 && isHave.size() == 0) {
                for (Map<String, Object> map : list) {
                    map.replace("Address", map.get("Address"), map.get("cityName").toString() + map.get("countyName").toString() + map.get("codeName").toString());
                    String address = map.get("cityName").toString() + map.get("countyName").toString() + map.get("codeName").toString();
                    map.put("areaCode", map.get("cityCode").toString() + "," + map.get("countyCode").toString() + "," + map.get("code").toString());
                    tabMonitorPersonMapper.updateAddress(address, map.get("id").toString());
                }
                PageHelper.startPage(vo.getPage(), vo.getLimit());
                PageHelper.orderBy("id desc");
                list1 = tabMonitorPersonMapper.getMonitorPersonList(vo);
            }

        }


        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list1);
        result.setCount((int) pageInfo.getTotal());
        result.setData(pageInfo.getList());
        result.setMsg("查询成功");
        return result;

    }

    @Override
    public Result addMonitorPerson(TabMonitorPersonVo vo) {
        Result result = new Result();
        if (vo.getName().equals("") || vo.getName() == null) {
            return result.failure(-1, "监测人姓名不能为空");
        }
        if (vo.getPhone().equals("") || vo.getPhone() == null) {
            return result.failure(-1, "监测人电话不能为空");
        }
        int i = tabMonitorPersonMapper.addMonitorPerson(vo);
        result.setData(i);
        result.setCode(0);
        result.setMsg("新增成功");
        return result;
    }

    @Override
    public Result updateMonitorPerson(TabMonitorPersonVo vo) {
        Result result = new Result();
        if (vo.getName().equals("") || vo.getName() == null) {
            return result.failure(-1, "监测人姓名不能为空");
        }
        if (vo.getPhone().equals("") || vo.getPhone() == null) {
            return result.failure(-1, "监测人电话不能为空");
        }
        int i = tabMonitorPersonMapper.updateMonitorPerson(vo);
        result.setData(i);
        result.setCode(0);
        result.setMsg("修改成功");
        return result;
    }

    @Override
    public Result deleteMonitorPerson(TabMonitorPersonVo vo) {
        if (vo.getId() == null || "".equals(vo.getId())) {
            return new Result().failure(-1, "请选择一条数据进行操作");
        }
        String[] ids = vo.getId().split(",");
        for (String idStr : ids) {
            tabMonitorPersonMapper.deleteMonitorPerson(Integer.parseInt(idStr));
        }
        return new Result().success("删除成功");
    }

}
